<!-- 编辑放置目标 -->
<template>
  <div>
    <a-modal :title="$t('新增标签')" v-model="modalVisible" width='35%' @ok="handleSubmit"
      @cancel="handleCancel" :maskClosable="false" v-dragModal>
      <a-form :form="form">
        <a-form-item :label="$t('Storage-area')" v-bind="formLayout">
          <a-input disabled v-decorator="['store_area', {
            rules: [
              // { required:true, message:$t('Enter')+$t('Storage-area') }
              // {pattern:namePattern,message:$t('Not_enter_special_characters')}
            ],
            initialValue: currentPlacementTarget.name
          }]" :placeholder="$t('Enter') + $t('Storage-area')" allowClear>
          </a-input>
        </a-form-item>
        <!-- 存储标签 -->
        <a-form-item :label="$t('Store-label')" v-bind="formLayout">
          <a-row :gutter="9">
            <a-col :span="20">
              <a-input v-decorator="['store_label', {
                rules: [
                  // {pattern:namePattern,message:$t('Not_enter_special_characters')}
                ],
              }]" :placeholder="$t('Add-label-tip')" @change="changeLabelName" allowClear>
              </a-input>
            </a-col>
            <a-col :span="3">
              <a-button class="add-button-normal" @click="addCustomLabel">{{ $t('Add') }}</a-button>
            </a-col>
          </a-row>
          <div class="label-box">
            <!-- 默认标签 -->
            <!-- <span class="default-label-box">
              STANDARD<span>({{$t('Default')}})</span>
            </span> -->
            <span class="default-label-box" v-for="item in alllabel">
              <span v-if="item == 'STANDARD'"> STANDARD({{ $t('Default') }})</span>
              <span v-else>{{ item }}</span>
            </span>
            <transition-group name="label-fade">
              <div class="custom-label-box" v-for="(item, index) in customLabels" :key="item.value"
                @click="showEditLabel(item)">
                <div v-if="!item.isShowEdit">
                  <span>{{ item.value }}</span>
                  <span class="del-label-icon" @click="delCustomLabel(index)">x</span>
                </div>
                <a-input v-if="item.isShowEdit" v-model="editLabelValue" style="width:80px;height:22px"
                  @blur="handleEditLabel(item)"></a-input>
              </div>
            </transition-group>
          </div>
          <span class="add-label-tip" v-if="isShowAddLabelTip">
            {{ $store.state.language == 'zh' ? '已存在同名的标签！' : 'A label with the same name already exists!' }}
          </span>
        </a-form-item>
      </a-form>
      <template slot="footer">
        <a-button @click="handleReset" class="submit-btn">
          {{ $t('Reset') }}
        </a-button>
        <a-button class="submit-btn" type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ $t('Sure') }}
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
export default {
  name: "EditPlacementTarget",
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    currentPlacementTarget: {
      type: Object
    },
    targetArea: {
      type: Object,
      required: true,
      default: () => { return {} }
    }
  },
  data() {
    return {
      modalVisible: false,
      form: this.$form.createForm(this),
      submitLoading: false,
      formLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 17 }
      },
      labelInputName: '',
      customLabels: [],
      alllabel: [],
      customLabels_copy: [
        { value: "标签01", isShowEdit: false },
        { value: "标签02", isShowEdit: false },
        { value: "标签03", isShowEdit: false },
        { value: "标签04", isShowEdit: false },
        { value: "标签05", isShowEdit: false },
        { value: "标签06", isShowEdit: false },
      ],
      isShowAddLabelTip: false,
      editLabelValue: '',
      editingLabelNum: 0,
    }
  },

  watch: {
    visible(newValue) {
      this.getCurrentLabels();
      this.modalVisible = newValue;
    },
  },

  methods: {
    // 初始化当前编辑所拥有的标签
    getCurrentLabels() {
      console.log("get", this.currentPlacementTarget)
      this.alllabel = this.currentPlacementTarget.storage_classes
      // let labels = [];
      // this.currentPlacementTarget.storage_classes.forEach((item, index) => {
      //   if (index != 0) {
      //     labels.push({
      //       value: item,
      //       isShowEdit: false
      //     })
      //   }
      // })
      // this.customLabels = [...labels];
    },

    // 提交编辑放置目标
    handleSubmit() {
      this.form.validateFields(async (err, value) => {
        if (!err) {
          this.submitLoading = true;
          // let labels = ['STANDARD'];
          let labels = [];
          this.alllabel.forEach(item => {
            labels.push(item)
          })
          this.customLabels.forEach(item => {
            labels.push(item.value)
          })
          const params = {
            // zonegroup_id: "2fbe6ddb-4fe0-4cf3-a8d7-4da38bcb1546",
            // zonegroup_name: "pentastor",
            // name: "default-placement",
            // storage_classes: ["STANDARD", "vvv"],
            // id: 1
          zonegroup_id: this.targetArea.zonegroup_id,
          zonegroup_name: this.targetArea.zonegroup_name,
          name: value.store_area,
          storage_classes: labels,
          id: this.currentPlacementTarget.id
        }
        const res = await this.$api.areaManage.editAreaGroupAreaRequest(params);
        if (res && res.data) {
          this.model(res.data.id) //返回模板
          this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
          if (res.data.flag !== 1) {
            this.$emit('updateGroupStoreArea');
          }
        }
        this.customLabels = []
        this.handleCancel();
        this.submitLoading = false;
      }
      })
  },

  // 判断是否有同名标签
  hasSameLabel(label) {
    // return this.customLabels.some(item => {
    //   return label === item.value;
    // })
    const isInCustomLabels = this.customLabels.some(item => item.value === label);

    // 检查 allLabels 数组是否有匹配项
    const isInAllLabels = this.alllabel.includes(label);

    // 返回一个包含两个布尔值的对象，表示在两个数组中的匹配情况
    return isInCustomLabels || isInAllLabels
  },

  //改变标签名
  changeLabelName(e) {
    this.labelInputName = e.target.value;
  },

  //添加自定义标签
  addCustomLabel() {
    if (this.hasSameLabel(this.labelInputName)) {
      console.log("lainn", this.labelInputName)
      this.isShowAddLabelTip = true;
    }
    if (this.labelInputName && !this.hasSameLabel(this.labelInputName)) {
      console.log("!lainn", this.labelInputName)
      this.isShowAddLabelTip = false;
      this.customLabels.push(
        { value: this.labelInputName, isShowEdit: false },
      );
      this.form.resetFields(['store_label'])
      // this.alllabel.push(
      //   { value: this.labelInputName, isShowEdit: false },
      // );
    }
  },

  //删除自定义标签
  delCustomLabel(index) {
    this.customLabels.splice(index, 1);
  },

  //显示编辑自定义标签输入框
  showEditLabel(currentLabel) {
    this.editingLabelNum++;
    //只能存在一个修改输入框
    if (this.editingLabelNum > 1) {
      this.editingLabelNum = 1;
      return
    }
    this.editLabelValue = currentLabel.value;
    currentLabel.isShowEdit = true;
    //让输入框获取焦点
    this.$nextTick(() => {
      const editInputDom = document.querySelector('.custom-label-box > input');
      editInputDom.focus();
    })
  },

  //完成编辑自定义标签
  handleEditLabel(currentLabel) {
    //如果有相同名字的标签而且当前的标签名不是当前输入的新值
    if (this.hasSameLabel(this.editLabelValue) && (this.editLabelValue != currentLabel.value)) {
      this.isShowAddLabelTip = true;
      return;
    }
    currentLabel.value = this.editLabelValue;
    currentLabel.isShowEdit = false;
    this.isShowAddLabelTip = false;
    this.editingLabelNum = 0;
  },

  //重置表单
  handleReset() {
    this.form.resetFields(); //重置弹窗
    this.isShowAddLabelTip = false;
    this.customLabels = []
  },

  //关闭弹窗
  handleCancel() {
    this.$emit('closeOperateModal', 'edit-placement-target');
    this.form.resetFields(); //重置弹窗
    this.isShowAddLabelTip = false;
    this.customLabels = []
  },
},
}
</script>
<style scoped>
.add-button-normal {
  border: 1px solid var(--themeColor);
  color: var(--themeColor);
}

.label-box {
  height: 128px;
  background-color: #edf0f2;
  overflow: auto;
  padding: 0 5px 5px;
  box-sizing: border-box;
}

.default-label-box,
.custom-label-box {
  display: inline-block;
  margin: 0 2px;
  border: 1px solid #666666;
  border-radius: 3px;
  color: #333;
  padding: 3px 6px;
  line-height: 14px;
}

.default-label-box {
  background-color: transparent;
}

.custom-label-box {
  background-color: #fff;
  transition: all 1s ease;
}

.custom-label-box span:nth-child(1) {
  margin-right: 8px;
}

.del-label-icon {
  float: right;
  color: #666;
  cursor: pointer;
  line-height: 12px;
}

.add-label-tip {
  color: var(--mainRedColor);
}

.submit-btn {
  width: 70px;
}

/* .label-fade-enter-active {
    
  } */
.label-fade-leave-active {
  position: absolute;
  /* transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0); */
}

.label-fade-enter,
.label-fade-leave-to

/* .slide-fade-leave-active for below version 2.1.8 */
  {
  opacity: 0;
  transform: translateY(30px);
}
</style>